package com.polaris.live.viewmodel.me

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.network.request
import com.polaris.live.common.network.requestLoading
import com.polaris.live.common.network.state.ResultState
import com.polaris.live.im.sfs.bean.live.ext.UserBasicVo
import com.polaris.live.net.userService
import com.polaris.live.resp.back_resp.UserInviteHostListResp
import com.polaris.live.resp.back_resp.UserInviteResp
import com.polaris.live.resp.go_resp.JoinInviteAgencyBean
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.time.Duration.Companion.milliseconds

/**
 * AgencyInviteModel
 *
 * @author Created by lucas on 2023/10/16 10:15
 * @since 1.0.0
 */
class AgencyInviteModel : BaseViewModel() {

    val agencyUserLiveData = MutableLiveData<ResultState<UserBasicVo>>()
    val joinAgencyLiveData = MutableLiveData<ResultState<UserInviteResp>>()
    val inviteMeLiveData = MutableLiveData<ResultState<List<UserInviteHostListResp>>>()

    private var fetchInviteUserJob: Job? = null

    fun getInviter(agencyCode: String) {
        fetchInviteUserJob?.cancel()
        fetchInviteUserJob = viewModelScope.launch {
            try {
                delay(500.milliseconds)
                request({ userService.getInviterUser(agencyCode) }, agencyUserLiveData)
            } finally {
                if (fetchInviteUserJob == coroutineContext[Job]) {
                    fetchInviteUserJob = null
                }
            }
        }
    }
    fun joinInviterAgency(agencyCode: String) {
        requestLoading(
            { userService.joinInviterAgency(JoinInviteAgencyBean(agencyCode)) },
            joinAgencyLiveData
        )
    }

    fun agencyInviteMeList() {
        request({ userService.getInviteList() }, inviteMeLiveData)
    }
}